package cn.wen233.srpc.core.serialize;

import cn.wen233.srpc.basic.model.Request;
import cn.wen233.srpc.basic.model.Response;
import cn.wen233.srpc.basic.serialize.Serializer;
import cn.wen233.srpc.core.service.spi.Order;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.objenesis.strategy.SerializingInstantiatorStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;

/**
 * Kryo 序列化器
 *
 * @author wenei
 * @date 2021-10-29 15:34
 */
public class KryoSerializer implements Serializer {

    private static final Logger LOGGER = LoggerFactory.getLogger(KryoSerializer.class);

    /**
     * 由于Kryo不是线程安全的，所以给每个线程都设置一个单独的Kryo
     */
    public static ThreadLocal<Kryo> kryoThreadLocal = ThreadLocal.withInitial(() -> {
        Kryo kryo = new Kryo();
        return kryo;
    });


    @Override
    public byte[] serialize(Object obj) {
        byte[] buffer = new byte[1024 * 1024];
        Output output = new Output(buffer);
        // 将对象装换成outputSteam从而变成byte[]
        Kryo kryo = kryoThreadLocal.get();
        kryo.writeObject(output, obj);
        return output.toBytes();
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        Input input = new Input(bytes);
        Kryo kryo = kryoThreadLocal.get();
        return kryo.readObject(input, clazz);
    }
}
